package com.amokgames.tictactoe;

import android.util.Log;

enum Turn {
	empty,
	x,
	o
}

public class GameEngine {
	Turn board[][];
	Turn turn;
	MessageSender messageSender;

	public GameEngine(MessageSender messageSender) {
		this.messageSender = messageSender;
		reset();
	}

	Turn getPiece(int x, int y) {
		return board[x][y];
	}
	
	void setPiece(int x, int y, Turn piece)	{
		board[x][y] = piece;
	}
	
	Turn getTurn() {
		return turn;
	}
	
	void nextTurn() {
		if(turn == Turn.x) turn = Turn.o;
		else turn = Turn.x;
	}
	
	public void reset() {
		board = new Turn[3][3];
		for(int y = 0; y < 3; y++)
			for(int x = 0; x < 3; x++)
				board[x][y] = Turn.empty;
		turn = Turn.x;
	}

	public void handleClick(int x, int y) {
		if(!gameOver() && board[x][y] == Turn.empty) {
			board[x][y] = turn;
			nextTurn();
			if(null != messageSender) {
				messageSender.send("" + x + ":" + y);
			}
			else {
				Log.e("BT", "ERROR messageSender = null");
			}
		}
	}

	public boolean gameOver() {
		return didPlayerWin(Turn.x) || didPlayerWin(Turn.o) || boardFull(); 
	}
	
	public boolean boardFull() {
		for(int y = 0; y < 3; y++)
			for(int x = 0; x < 3; x++)
				if(board[x][y] == Turn.empty)
					return false;
		return true;
	}

	public boolean didPlayerWin(Turn turn) {
		for(int y = 0; y < 3; y++)
			if(turn == board[0][y] && turn == board[1][y] && turn == board[2][y])
				return true;
		
		for(int x = 0; x < 3; x++)
			if(turn == board[x][0] && turn == board[x][1] && turn == board[x][2])
				return true;

		if(turn == board[0][0] && turn == board[1][1] && turn == board[2][2])
			return true;
		
		if(turn == board[0][2] && turn == board[1][1] && turn == board[2][0])
			return true;
		
		return false;
	}

	public Turn getState(int x, int y) {
		return board[x][y];
	}
}
